if(!/^http(s*):\/\//.test(location.href)) {
    alert('请通过 localhost 访问');
    window.close();
}

class utils {
    options(options) {
        return new Function("return " + options)()
    }

    clearCache() {
        localStorage.removeItem('TOKEN');
        localStorage.removeItem('USERINFO');
        localStorage.removeItem('PERMISSIONS');
        localStorage.removeItem('MENUS');
        localStorage.removeItem('WEBSITE');
    }

    getSystemUser() {
        return JSON.parse(CryptoJS.enc.Base64.parse(localStorage.getItem('USERINFO')).toString(CryptoJS.enc.Utf8));
    }

    getSystemPermissions() {
        return JSON.parse(CryptoJS.enc.Base64.parse(localStorage.getItem('PERMISSIONS')).toString(CryptoJS.enc.Utf8));
    }

    getSystemMenus() {
        return JSON.parse(CryptoJS.enc.Base64.parse(localStorage.getItem('MENUS')).toString(CryptoJS.enc.Utf8));
    }

    getSystemConfig() {
        return JSON.parse(CryptoJS.enc.Base64.parse(localStorage.getItem('WEBSITE')).toString(CryptoJS.enc.Utf8));
    }

    htmlClearTags(str = '') {
        return str ? this.trim(str.replace(/<i\s*[^>]*>(.*?)<\/i>/ig,"")) : '';
    }

    inArray(value, list) {
        if (list && typeof list === 'object') {
            for (const item of list) {
                if (item === value) {
                    return true;
                }
            }
        }
        return false;
    }

    trim(str) {
        if (str && typeof str === 'string') {
            return str.replace(/(^\s*)|(\s*$)/g, "");
        }
        return '';
    }

    meta(metaName) {
        if (metaName && typeof metaName === 'string') {
            const metas = document.getElementsByTagName('meta');
            for (const item of metas) {
                if (item.getAttribute('name') === metaName) {
                    return item.getAttribute('content');
                }
            }
        }
        return '';
    }

    formatJson(json) {
        let formatted = '', padIdx = 0, PADDING = '    ';
        if (typeof json !== 'string') {
            json = JSON.stringify(json);
        }
        json = json.replace(/([\{\}])/g, '\r\n$1\r\n')
            .replace(/([\[\]])/g, '\r\n$1\r\n')
            .replace(/(\,)/g, '$1\r\n')
            .replace(/(\r\n\r\n)/g, '\r\n')
            .replace(/\r\n\,/g, ',');
        (json.split('\r\n')).forEach(function (node, index) {
            let indent = 0, padding = '';
            if (node.match(/\{$/) || node.match(/\[$/)) indent = 1;
            else if (node.match(/\}/) || node.match(/\]/))  padIdx = padIdx !== 0 ? --padIdx : padIdx;
            else  indent = 0;
            for (let i = 0; i < padIdx; i++) {
                padding += PADDING;
            }
            formatted += padding + node + '\r\n';
            padIdx += indent;
        });
        return formatted;
    }

    responseText(xhr) {
        const status = xhr.status, responseText = xhr.responseText;
        let message = '不好，有错误';
        switch (status) {
            case 400:
                message = responseText || '失败了';
                break;
            case 401:
                message = responseText || '你没有权限';
                break;
            case 403:
                message =  '你没有权限执行此操作!';
                break;
            case 404:
                message = '你访问的操作不存在';
                break;
            case 406:
                message = '请求格式不正确';
                break;
            case 410:
                message = '你访问的资源已被删除';
                break;
            case 422:
            case 423:
                const errors = xhr.responseJSON;
                let m = '';
                if (errors && typeof errors === 'object') {
                    for(const index in errors){
                        const item = errors[index];
                        if (typeof item === 'object') {
                            for(const i in item){
                                m += item[i] + '\r\n';
                            }
                            break;
                        }
                        m += item + '\r\n';
                    }
                }
                message = m;
                break;
            case 429:
                message = '超出访问频率限制';
                break;
            case 500:
                message = '500 INTERNAL SERVER ERROR';
                break;
        }
        return message;
    }

    handleMoney(price) {
        let AmountUnits = ["元", "万元", "亿", "兆", '京', '垓', '杼'], strum = price.toString(), AmountUnit = '';
        AmountUnits.find((item, index) => {
            let newNum = strum;
            if (strum.indexOf('.') !== -1) {
                newNum = strum.substring(0, strum.indexOf('.'))
            }
            if (newNum.length < 5) {
                return AmountUnit = item;
            }
            strum = (newNum * 1 / 10000).toString()
        })
        return (strum * 1) + AmountUnit;
    }

    queryVal(variable, def = '') {
        if (variable && typeof variable === 'string') {
            const query = window.location.search.substring(1), vars = query.split("&");
            for (const item in vars) {
                const pair = item.split("=");
                if(pair[0] === variable){
                    return pair[1] || def;
                }
            }
        }
        return def;
    }

    handlerUrl(url, query) {
        if ((url && typeof url === 'string') && (query && typeof query === 'object')) {
            let queryArr = [];
            for (const key in query) {
                if (query.hasOwnProperty(key)) {
                    queryArr.push(`${key}=${query[key]}`);
                }
            }
            return url.indexOf('?') !== -1 ? `${url}&${queryArr.join('&')}` : `${url}?${queryArr.join('&')}`;
        }
        return '';
    }

    parentId(data, parent_id) {
        if (data && typeof data === 'object') {
            for (const i in data) {
                if (parseInt(data[i].id) === parseInt(parent_id)) {
                    return parent_id;
                }else if (data[i].children && data[i].children.length > 0) {
                    return this.parentId(data[i].children, parent_id);
                }
            }
        }
        return 0;
    }

    listToTree(list, pk = 'id', pid = 'parent_id', child = '_child', root = 0) {
        if (list && typeof list === 'object') {
            let arr = [];
            if (list.length > 0) {
                for (const sorData of list) {
                    if (sorData[pid] === root) {
                        sorData[child] = this.listToTree(list, pk, pid, child, sorData[pk]);
                        arr.push(sorData);
                    }
                }
            }
            return arr;
        }
        return [];
    }

    imgError(image) {
        image.src = "./admin/img/nopic.png";
        image.onerror = null;
    }

    loadImage(src) {
        const that = this;
        return new Promise(function(resolve) {
            let img = new Image();
            img.onload = function() {
                resolve(img);
            }
            img.onerror = function() {
                that.imgError(this);
            }
            img.src = src;
        });
    }

    fileSize(size) {
        if (size && typeof size === 'number') {
            const num = 1024;
            if (size < num) {
                return size + "B";
            }
            if (size < Math.pow(num, 2)) {
                return (size / num).toFixed(2) + "K";
            }
            if (size < Math.pow(num, 3)) {
                return (size / Math.pow(num, 2)).toFixed(2) + "M";
            }
            if (size < Math.pow(num, 4)) {
                return (size / Math.pow(num, 3)).toFixed(2) + "G";
            }
            return (size / Math.pow(num, 4)).toFixed(2) + "T";
        }
        return "";
    }

    doAdmin() {
        const local = document.location, pathname = local.pathname;
        let baseUrl = local.origin;
        if (local.protocol === "http:") {
            baseUrl.replace("http:","");
        }else if (local.protocol === "https:") {
            baseUrl.replace("https:","");
        }
        if (pathname.indexOf("public") !== -1) {
            baseUrl += pathname.match(/.*\/public*/)[0];
        }
        if (pathname.indexOf("index.php") !== -1) {
            baseUrl += '/index.php';
        }
        return baseUrl;
    }

    storage(url, storage = 'local') {
        if (url && typeof url === 'string') {
            if (url.indexOf('static') !== -1) return './' + url.replace("static/","");
            if (url.indexOf("http") !== -1 || url.indexOf("https") !== -1) return url;
            url = url.indexOf('/') === 0 ? url.substr(1) : url;
            const config = this.getSystemConfig();
            const upload = config.upload || {};
            if (upload.storage) {
                storage = upload.storage;
            }
            if (upload[storage]) {
                return upload[storage].url + "/" + url;
            }
            let baseUrl = this.doAdmin();
            if (url.indexOf('storage') !== -1) {
                return baseUrl + "/" + url;
            }
            return baseUrl + "/storage/" + url;
        }
        return '';
    }

    route(url) {
        if (url && typeof url === 'string') {
            if (url.indexOf("http") !== -1 || url.indexOf("https") !== -1) return url;
            url = url.indexOf('/') === 0 ? url.substr(1) : url;
            return this.doAdmin() + "/" + url;
        }
        return '';
    }

    userCan(per) {
        if (per && typeof per === 'string') {
            const Permissions = this.getSystemPermissions();
            if (Permissions) {
                for (const item of Permissions) {
                    if (per === item) return true;
                }
            }
        }
        return false;
    }

    isHttp(url) {
        if (url && typeof url === 'string') {
            if (url.indexOf("http") !== -1 || url.indexOf("https") !== -1 || url.indexOf("//") !== -1) {
                return true;
            }
        }
        return false;
    }
}
const AppGeneral = new utils();
AppGeneral.localStorage = {
    setItem(key, value, expire = 7200) {
        if (isNaN(expire) || expire < 1) {
            throw new Error('有效期应为一个有效数值');
        }
        localStorage.setItem(key, JSON.stringify({
            data: value,
            time: Date.now(),
            expire: expire * 1000,
        }));
    },
    getItem(key) {
        let val = localStorage.getItem(key);
        if (!val) return val;
        val = JSON.parse(val);
        if (Date.now() > val.time + val.expire) {
            localStorage.removeItem(key);
            return '';
        }
        return val.data;
    }
}
AppGeneral.cookies = {
    cookie: {
        set: (name,value,expireTime) => {
            const exp = new Date();
            exp.setTime(exp.getTime() + expireTime*1000);
            document.cookie = name + "="+ escape(value) + ";expires=" + exp.toGMTString();
        },
        // 获取cookie
        get: (name) => {
            let arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
            return arr && arr.length > 0 ? arr[2] : "";
        },
        // 删除cookie
        remove: (name) => {
            this.set(name,'', -1)
        }
    }
}